package JDBC;

import java.sql.*;

/**
 * 关于查询语句的使用
 *
 *
 * @author Mc.Chai
 * @program: JavaWeb
 * @create 2021-12-13-20:17 20:17
 */
public class JdbcResultSet {

    public static void main(String[] args) {
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql:///cartoondb", "root", "123456");
            String sql="select * from user";
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            //游标默认位置在表头。让游标向下移动一行,进行判断是否数据
            while(resultSet.next()){
                //返回当前位置第一列数据
                String id = resultSet.getString(1);
                //返回当前位置字段为username的数据
                String username = resultSet.getString("username");
                String userpwd=resultSet.getString(3);
                String truename=resultSet.getString("truename");
                System.out.println("--"+id+"--"+username+"--"+userpwd+"--"+truename+"--");
            }

        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            //进行空指针异常的处理
            if (resultSet!=null){
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement!=null){
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (connection!=null){
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

        }
    }
}
